﻿using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;

namespace VisibilityControlLibrary
{
    [ContentProperty(Name = "Items")]
    public class VisibilityControl : ItemsControl
    {
        public VisibilityControl()
        {
            this.DefaultStyleKey = typeof(VisibilityControl);
            Items.VectorChanged += OnItemsChanged;
        }

        public bool IsTrue
        {
            get { return (bool)GetValue(IsTrueProperty); }
            set { SetValue(IsTrueProperty, value); }
        }

        public static readonly DependencyProperty IsTrueProperty =
            DependencyProperty.Register("IsTrue", typeof(bool), typeof(VisibilityControl), new PropertyMetadata(null, OnIsTrueChanged));

        public object VisibleContent
        {
            get { return (object)GetValue(VisibleContentProperty); }
            private set { SetValue(VisibleContentProperty, value); }
        }

        public static readonly DependencyProperty VisibleContentProperty =
            DependencyProperty.Register("VisibleContent", typeof(object), typeof(VisibilityControl), new PropertyMetadata(null));

        private static void OnIsTrueChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
        {
            var visibilityItemsControl = d as VisibilityControl;
            if (visibilityItemsControl != null)
            {
                visibilityItemsControl.Evaluate();
            }
        }

        void OnItemsChanged(IObservableVector<object> sender, IVectorChangedEventArgs evt)
        {
            Evaluate();
        }

        void Evaluate()
        {
            if (Items.Count >= 2)
            {
                VisibleContent = Items[IsTrue ? 1 : 0];
            }
            else
            {
                VisibleContent = null;
            }
        }
    }
}
